﻿using System.Collections.Generic;
using Reactor.Environment;
using Reactor.Messages.Events.Failures.Adoption;
using Reactor.Messaging;
using Samurai.Wakizashi.Extensions;

namespace Reactor.Services.AdvisoryEmailService
{
    public class ServiceAdoptionFailedHandler : MessageHandlerBase<AdoptionFailed>
    {
        #region Overrides of MessageHandlerBase<AdoptionFailed>

        public override void OnHandling(AdoptionFailed message, IMessageContext messageContext)
        {
            var svc = (Service) Context.GridContext.CurrentReactorService;
            var map = svc.GetEmailMap(typeof (AdoptionFailed).FullName);

            var emailTask = new EmailTask
                                {
                                    Body = string.Format(map.BodyFormatString, message.ToXml()),
                                    Cc = GetCcAddresses(map.Cc),
                                    From = GetFromAddress(),
                                    Subject = string.Format(map.SubjectFormatString, typeof (AdoptionFailed).Name),
                                    To = GetToAddresses(map.SendTo)
                                };
            svc.EnqueueEmailTask(emailTask);
        }

        #endregion

        private IEnumerable<string> GetToAddresses(string rawValue)
        {
            if (string.IsNullOrEmpty(rawValue)) return new string[0];

            var parts = rawValue.Split(';');
            return parts.Length == 0 ? new string[0] : parts;
        }

        private IEnumerable<string> GetCcAddresses(string rawValue)
        {
            if (string.IsNullOrEmpty(rawValue)) return new string[0];

            var parts = rawValue.Split(';');
            return parts.Length == 0 ? new string[0] : parts;
        }

        private string GetFromAddress()
        {
            var configValue = Context.Configuration.GetConfigurationValue("Services.AdvisoryEmailService.FromAddress");
            return !string.IsNullOrEmpty(configValue) ? configValue : "auto@reactor-project.net";
        }
    }
}
